package com.xxl.job.executor.service.jobhandler;

import com.ruoyi.bizsys.domain.CreditApply;
import com.ruoyi.bizsys.domain.LoanOrder;
import com.ruoyi.bizsys.service.ICreditApplyService;
import com.ruoyi.bizsys.service.ILoanOrderService;
import com.ruoyi.business.service.ICreditService;
import com.ruoyi.business.service.ILoanService;
import com.ruoyi.system.service.ISysConfigService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class AndonJob {

    @Autowired
    ICreditApplyService creditApplyService;

    @Autowired
    ILoanOrderService loanOrderService;

    @Autowired
    ICreditService creditService;

    @Autowired
    ILoanService loanService;

    @Autowired
    ISysConfigService sysConfigService;

    @XxlJob("andonJobHandler")
    public void execute() {
        XxlJobHelper.log("AndonJob Start >>>>>>>>>>");

        String andonTaskMinute = sysConfigService.selectConfigByKey("andon_task_minute");
        log.info("andonTaskMinute：{}", andonTaskMinute);

        againTriggerCredit(Integer.parseInt(andonTaskMinute));
        againTriggerLoan(Integer.parseInt(andonTaskMinute));

        XxlJobHelper.log("AndonJob End >>>>>>>>>>");
    }

    public void againTriggerCredit(Integer andonTaskMinute) {
        log.info("AndonJob.againTrigger[credit] >>> ");

        List<CreditApply> creditApplies = creditApplyService.getReturnRunCreditData(andonTaskMinute);
        log.info("creditApplies.size >>> {}", creditApplies.size());

        for (int i = 0; i < creditApplies.size(); i++) {
            try {
                creditService.againTrigger(creditApplies.get(i));
            } catch (Exception e) {
                XxlJobHelper.log("AndonJob.againTrigger[credit] error：");
                XxlJobHelper.log(e);
            }
        }
    }

    public void againTriggerLoan(Integer andonTaskMinute) {
        log.info("AndonJob.againTrigger[loan] >>> ");

        List<LoanOrder> loanOrders = loanOrderService.getReturnRunLoanData(andonTaskMinute);
        log.info("loanOrders.size >>> {}", loanOrders.size());

        for (int i = 0; i < loanOrders.size(); i++) {
            try {
                loanService.againTrigger(loanOrders.get(i));
            } catch (Exception e) {
                XxlJobHelper.log("AndonJob.againTrigger[loan] error：");
                XxlJobHelper.log(e);
            }
        }
    }

}
